package com.iwaster.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * wgy 2019/4/22 16:31
 */
public class DataSourceUtils {
    private static DruidDataSource dataSource;
    //线程局部变量
    private static ThreadLocal<Connection> threadLocal;


    static {
        try {
            threadLocal=new ThreadLocal<>();
            Properties properties=new Properties();
            InputStream is= DataSourceUtils.class.getClassLoader().getResourceAsStream("database.properties");
            properties.load(is);

            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败");
        }


    }

    public static DataSource getDataSource(){
        return dataSource;
    }


    //获取连接
    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection==null){
            connection=getDataSource().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

    //开启事务
    public static void startTransaction() throws SQLException{
        Connection connection = getConnection();
        connection.setAutoCommit(false);
    }
    //提交
    public static void commit() throws SQLException{
        Connection connection = getConnection();
        connection.commit();
    }

    //回滚
    public static void rollback() throws SQLException{
        Connection connection = getConnection();
        connection.rollback();
        connection.commit();
    }
    //关闭
    public static void close() throws SQLException{
        Connection connection = getConnection();
        connection.close();
        threadLocal.remove();

    }
}
